package com.zk;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;

/**
 * @author: sun.hongliang
 * @create: 2019/10/10 12:03
 */
public class ZkUtils {

    public static boolean replace(CuratorFramework client, String path, String value) throws Exception {
        if (client.checkExists().forPath(path) != null) {
            client.setData().forPath(path, value.getBytes());
        } else {
            client.create().creatingParentsIfNeeded().forPath(path, value.getBytes());
        }
        return true;
    }

    public static boolean replaceEphemeral(CuratorFramework client, String path, String value) throws Exception {
        if (client.checkExists().forPath(path) != null) {
            client.setData().forPath(path, value.getBytes());
        } else {
            client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path, value.getBytes());
        }
        return true;
    }


    public static boolean createIfNoNode(CuratorFramework client, String path, String value) throws Exception {
        if (client.checkExists().forPath(path) != null) {
            // 节点存在 , noop！
        } else {
            client.create().creatingParentsIfNeeded().forPath(path, value.getBytes());
        }
        return true;
    }

    public static String getStringData(CuratorFramework client, String path) {
        try {
            return new String(client.getData().forPath(path));
        } catch (Exception e) {
            return null;
        }
    }

    public static boolean checkExists(CuratorFramework client, String path) throws Exception {
        if (client.checkExists().forPath(path) != null) {
            return true;
        } else {
            return false;
        }
    }

}
